<template>
  <div class="chat-container">
    <!-- 消息展示区域 -->
    <div class="messages" ref="messagesContainer">
      <div 
        v-for="(message, index) in messages"
        :key="index"
        :class="['message', message.sender]"
      >
        <div class="bubble">{{ message.content }}</div>
        <div class="timestamp">{{ formatTime(message.timestamp) }}</div>
      </div>
    </div>

    <!-- 消息输入区域 -->
    <div class="input-area">
      <input
        v-model="newMessage"
        @keyup.enter="sendMessage"
        placeholder="输入消息..."
      />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue';

// 消息数据
const messages = reactive([
  { 
    content: '您好！有什么可以帮您？',
    sender: 'bot',
    timestamp: new Date()
  }
]);

// 新消息内容
const newMessage = ref('');
// 获取消息容器DOM
const messagesContainer = ref(null);

// 发送消息
const sendMessage = () => {
  if (!newMessage.value.trim()) return;

  // 添加用户消息
  messages.push({
    content: newMessage.value,
    sender: 'user',
    timestamp: new Date()
  });

  fetch('http://localhost:8090/ai/generateStream?message=' + newMessage.value, {
      responseType: 'stream'
    }).then(async response => {
      const reader = response.body.getReader();
      const decoder = new TextDecoder('utf-8');
      let num = 0;
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        let chunk = decoder.decode(value, { stream: true });
        if(chunk.includes('data:<think>')) {
          chunk = chunk.replace('data:<think>', '');
        } else if(chunk.includes('data:</think>')) {
          chunk = chunk.replace('data:</think>', '');
        } else if(chunk.includes('data:')) {
          chunk = chunk.replaceAll('data:', '');
        }
        if(num === 0) {
          messages.push({
            content: chunk,
            sender: 'bot',
            timestamp: new Date()
          });
        } else {
          const messagesIndex = messages.length - 1;
          messages[messagesIndex].content += chunk;
          messages[messagesIndex].sender = 'bot';
          messages[messagesIndex].timestamp = new Date();
        }
        num ++;
      }
    })
  // 清空输入框并滚动到底部
  newMessage.value = '';
  nextTick(scrollToBottom);
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTo({
      top: messagesContainer.value.scrollHeight,
      behavior: 'smooth'
    });
  }
};

// 时间格式化函数
const formatTime = (date) => {
  return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
};
</script>

<style scoped>
.chat-container {
  width: 400px;
  height: 600px;
  border: 1px solid #ccc;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  margin: 20px auto;
  background: #f5f5f5;
}

.messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message {
  max-width: 80%;
  display: flex;
  flex-direction: column;
}

.message.user {
  align-self: flex-end;
}

.message.bot {
  align-self: flex-start;
}

.bubble {
  padding: 12px 18px;
  border-radius: 15px;
  line-height: 1.4;
}

.message.user .bubble {
  background: #4CAF50;
  color: white;
  border-bottom-right-radius: 3px;
}

.message.bot .bubble {
  background: #2196F3;
  color: white;
  border-bottom-left-radius: 3px;
}

.timestamp {
  font-size: 0.8em;
  color: #666;
  padding: 4px 10px;
}

.input-area {
  padding: 15px;
  border-top: 1px solid #ddd;
  display: flex;
  gap: 10px;
  background: white;
}

input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
}

button {
  padding: 10px 20px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}

button:hover {
  background: #45a049;
}
</style>